package com.example.friend.service.user;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.Constants;
import com.example.common.core.domain.TableDataInfo;
import com.example.common.core.enums.ExamListType;
import com.example.common.core.enums.ResultCode;
import com.example.common.core.utils.ThreadLocalUtil;
import com.example.friend.domain.exam.Exam;
import com.example.friend.domain.exam.dto.ExamDTO;
import com.example.friend.domain.exam.dto.ExamQueryDTO;
import com.example.friend.domain.exam.vo.ExamVO;
import com.example.friend.domain.user.UserExam;
import com.example.friend.manager.ExamCacheManager;
import com.example.friend.mapper.exam.ExamMapper;
import com.example.friend.mapper.user.UserExamMapper;
import com.example.security.exception.ServiceException;
import com.example.security.service.TokenService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 23050
 * @version 1.0
 * @description: TODO
 * @date 2025/3/11 19:52
 */
@Service
public class UserExamServiceImpl implements UserExamService{

    @Resource
    private UserExamMapper userExamMapper;

    @Resource
    private ExamMapper examMapper;

    @Resource
    private TokenService tokenService;

    @Resource
    private ExamCacheManager examCacheManager;

    @Value("${jwt.secret}")
    private String secret;

    //报名竞赛
    @Override
    public int enter(String token, ExamDTO examDTO) {
        //判断是否存在这个竞赛
        Exam exam = examMapper.selectById(examDTO.getExamId());
        if (exam == null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        //判断是否开赛
        if (exam.getStartTime().isBefore(LocalDateTime.now())){
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
        //从token里面获取userid
//        Long userId = tokenService.getUserId(token,secret);
        //从ThreadLocal里面获取拦截器解析userId
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        //判断是否已经报名过
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examDTO.getExamId())
                .eq(UserExam::getUserId, userId));
        if (userExam!=null){
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        //往缓存里面存储
        examCacheManager.addUserExamCache(userId, examDTO.getExamId());

        //往数据库里面存储
        userExam = new UserExam();
        userExam.setExamId(examDTO.getExamId());
        userExam.setUserId(userId);
        int ret = userExamMapper.insert(userExam);
        return  ret;
    }



    //查询用户自己报名的竞赛列表
    //查询redis中的用户已报名竞赛列表
    @Override
    public TableDataInfo redisList(ExamQueryDTO examQueryDTO) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        //判断redis中的 未完赛或历史竞赛 的list是否有数据
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(),userId);
        List<ExamVO> examVOList;
        if (total == null || total ==0){
            //走数据库查询
            PageHelper.startPage(examQueryDTO.getPageNum(),examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            //如果redis中没有数据 刷新缓存
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(),userId);
            total = new PageInfo<>(examVOList).getTotal();
        }else{
            //从redis中获取数据
            examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
            examVOList = examCacheManager.getExamVOList(examQueryDTO,userId);
            total = examCacheManager.getListSize(examQueryDTO.getType(),userId);
        }
        if (CollectionUtil.isEmpty(examVOList)){
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList,total);
    }



}









